package com.iplant.aps.serviceimpl.dao.rsm;

import com.iplant.aps.service.mesenum.MESDBSource;
import com.iplant.aps.service.mesenum.MESException;
import com.iplant.aps.service.po.OutResult;
import com.iplant.aps.service.po.ServiceResult;
import com.iplant.aps.service.po.bms.BMSEmployee;
import com.iplant.aps.service.po.rsm.RSMTurnOrderDesc;
import com.iplant.aps.service.utils.StringUtils;
import com.iplant.aps.serviceimpl.dao.BaseDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

import java.text.MessageFormat;
import java.util.*;

public class RSMTurnOrderDescDAO extends BaseDAO {

    private static final Logger logger = LoggerFactory.getLogger(RSMTurnOrderDescDAO.class);

    private static RSMTurnOrderDescDAO Instance = null;

    private RSMTurnOrderDescDAO() {
        super();
    }

    public static RSMTurnOrderDescDAO getInstance() {
        if (Instance == null)
            Instance = new RSMTurnOrderDescDAO();
        return Instance;
    }

    /**
     * 添加或修改
     */
    public int Update(BMSEmployee wLoginUser, RSMTurnOrderDesc wRSMTurnOrderDesc, OutResult<Integer> wErrorCode) {
        int wResult = 0;
        try {
            ServiceResult<String> wInstance = this.GetDataBaseName(wLoginUser.getCompanyID(), MESDBSource.Basic,
                    wLoginUser.getID(), 0);
            wErrorCode.set(wInstance.ErrorCode);
            if (wErrorCode.Result != 0) {
                return wResult;
            }

            if (wRSMTurnOrderDesc == null)
                return 0;

            String wSQL = "";
            if (wRSMTurnOrderDesc.getID() <= 0) {
                wSQL = MessageFormat.format("INSERT INTO {0}.rsm_turnorderdesc(OrderID,PartID,PartPointID," +
                                "IsMaterialShortage,Remark,CreateID,CreateTime,EditID,EditTime) VALUES(:OrderID," +
                                ":PartID,:PartPointID,:IsMaterialShortage,:Remark,:CreateID,:CreateTime,:EditID," +
                                ":EditTime);",
                        wInstance.Result);
            } else {
                wSQL = MessageFormat.format("UPDATE {0}.rsm_turnorderdesc SET OrderID = :OrderID,PartID = :PartID," +
                                "PartPointID = :PartPointID,IsMaterialShortage = :IsMaterialShortage,Remark = " +
                                ":Remark,CreateID = :CreateID,CreateTime = :CreateTime,EditID = :EditID,EditTime = " +
                                ":EditTime WHERE ID = :ID;",
                        wInstance.Result);
            }

            wSQL = this.DMLChange(wSQL);

            Map<String, Object> wParamMap = new HashMap<String, Object>();

            wParamMap.put("ID", wRSMTurnOrderDesc.ID);
            wParamMap.put("OrderID", wRSMTurnOrderDesc.OrderID);
            wParamMap.put("PartID", wRSMTurnOrderDesc.PartID);
            wParamMap.put("PartPointID", wRSMTurnOrderDesc.PartPointID);
            wParamMap.put("IsMaterialShortage", wRSMTurnOrderDesc.IsMaterialShortage);
            wParamMap.put("Remark", wRSMTurnOrderDesc.Remark);
            wParamMap.put("CreateID", wRSMTurnOrderDesc.CreateID);
            wParamMap.put("CreateTime", wRSMTurnOrderDesc.CreateTime);
            wParamMap.put("EditID", wRSMTurnOrderDesc.EditID);
            wParamMap.put("EditTime", wRSMTurnOrderDesc.EditTime);

            KeyHolder keyHolder = new GeneratedKeyHolder();
            SqlParameterSource wSqlParameterSource = new MapSqlParameterSource(wParamMap);

            shrisJdbcTemplate.update(wSQL, wSqlParameterSource, keyHolder);

            if (wRSMTurnOrderDesc.getID() <= 0) {
                wResult = Objects.requireNonNull(keyHolder.getKey()).intValue();
                wRSMTurnOrderDesc.setID(wResult);
            } else {
                wResult = wRSMTurnOrderDesc.getID();
            }
        } catch (Exception ex) {
            wErrorCode.set(MESException.DBSQL.getValue());
            logger.error(ex.toString());
        }
        return wResult;
    }

    /**
     * 删除集合
     */
    public ServiceResult<Integer> DeleteList(BMSEmployee wLoginUser, List<RSMTurnOrderDesc> wList,
                                             OutResult<Integer> wErrorCode) {
        ServiceResult<Integer> wResult = new ServiceResult<Integer>(0);
        try {
            ServiceResult<String> wInstance = this.GetDataBaseName(wLoginUser.getCompanyID(), MESDBSource.Basic,
                    wLoginUser.getID(), 0);
            wErrorCode.set(wInstance.ErrorCode);
            if (wErrorCode.Result != 0) {
                return wResult;
            }

            if (wList == null || wList.size() <= 0)
                return wResult;

            List<String> wIDList = new ArrayList<String>();
            for (RSMTurnOrderDesc wItem : wList) {
                wIDList.add(String.valueOf(wItem.ID));
            }
            String wSql = MessageFormat.format("delete from {1}.rsm_turnorderdesc WHERE ID IN({0}) ;",
                    String.join(",", wIDList), wInstance.Result);
            this.ExecuteSqlTransaction(wSql);
        } catch (Exception ex) {
            wErrorCode.set(MESException.DBSQL.getValue());
            logger.error(ex.toString());
        }
        return wResult;
    }

    /**
     * 查单条
     */
    public RSMTurnOrderDesc SelectByID(BMSEmployee wLoginUser, int wID, OutResult<Integer> wErrorCode) {
        RSMTurnOrderDesc wResult = new RSMTurnOrderDesc();
        try {
            ServiceResult<String> wInstance = this.GetDataBaseName(wLoginUser.getCompanyID(), MESDBSource.Basic,
                    wLoginUser.getID(), 0);
            wErrorCode.set(wInstance.ErrorCode);
            if (wErrorCode.Result != 0) {
                return wResult;
            }

            List<RSMTurnOrderDesc> wList = SelectList(wLoginUser, wID, -1, -1, -1, -1, wErrorCode);
            if (wList == null || wList.size() != 1)
                return wResult;
            wResult = wList.get(0);
        } catch (Exception e) {
            wErrorCode.set(MESException.DBSQL.getValue());
            logger.error(e.toString());
        }
        return wResult;
    }

    /**
     * 条件查询集合
     */
    public List<RSMTurnOrderDesc> SelectList(BMSEmployee wLoginUser, int wID, int wOrderID, int wPartID,
                                             int wPartPointID, int wIsMaterialShortage, OutResult<Integer> wErrorCode) {
        List<RSMTurnOrderDesc> wResultList = new ArrayList<RSMTurnOrderDesc>();
        try {
            ServiceResult<String> wInstance = this.GetDataBaseName(wLoginUser.getCompanyID(), MESDBSource.Basic,
                    wLoginUser.getID(), 0);
            wErrorCode.set(wInstance.ErrorCode);
            if (wErrorCode.Result != 0) {
                return wResultList;
            }

            String wSQL = MessageFormat.format(
                    "SELECT t.*,t1.PartNo,t1.LineID,t3.Name LineName,t1.ProductID,t2.ProductNo,t4.ID CustomerID," +
                            "t4.CustomerName,t5.Name Creator,t6.Name Editor,t7.Name PartName,t8.Name " +
                            "PartPointName FROM {0}.rsm_turnorderdesc t "
                            + " left join {0}.oms_order t1 on t.OrderID=t1.ID "
                            + " left join {0}.fpc_product t2 on t1.ProductID=t2.ID "
                            + " left join {0}.fmc_line t3 on t1.LineID=t3.ID "
                            + " left join {0}.crm_customer t4 on t1.BureauSectionID=t4.ID "
                            + " left join {0}.mbs_user t5 on t.CreateID=t5.ID "
                            + " left join {0}.mbs_user t6 on t.EditID=t6.ID "
                            + " left join {0}.fpc_part t7 on t.PartID=t7.ID "
                            + " left join {0}.fpc_partpoint t8 on t.PartPointID=t8.ID "
                            + "WHERE  1=1  " +
                            "and ( :wID <= 0 or :wID = t.ID ) " +
                            "and ( :wOrderID <= 0 or :wOrderID = t.OrderID ) " +
                            "and ( :wPartID <= 0 or :wPartID = t.PartID ) " +
                            "and ( :wPartPointID <= 0 or :wPartPointID = t.PartPointID ) " +
                            "and ( :wIsMaterialShortage <= 0 or :wIsMaterialShortage = t.IsMaterialShortage );",
                    wInstance.Result);

            Map<String, Object> wParamMap = new HashMap<String, Object>();

            wParamMap.put("wID", wID);
            wParamMap.put("wOrderID", wOrderID);
            wParamMap.put("wPartID", wPartID);
            wParamMap.put("wPartPointID", wPartPointID);
            wParamMap.put("wIsMaterialShortage", wIsMaterialShortage);

            wSQL = this.DMLChange(wSQL);

            List<Map<String, Object>> wQueryResult = shrisJdbcTemplate.queryForList(wSQL, wParamMap);

            for (Map<String, Object> wReader : wQueryResult) {
                RSMTurnOrderDesc wItem = new RSMTurnOrderDesc();

                wItem.ID = StringUtils.parseInt(wReader.get("ID"));
                wItem.OrderID = StringUtils.parseInt(wReader.get("OrderID"));
                wItem.PartID = StringUtils.parseInt(wReader.get("PartID"));
                wItem.PartPointID = StringUtils.parseInt(wReader.get("PartPointID"));
                wItem.IsMaterialShortage = StringUtils.parseInt(wReader.get("IsMaterialShortage"));
                wItem.Remark = StringUtils.parseString(wReader.get("Remark"));
                wItem.CreateID = StringUtils.parseInt(wReader.get("CreateID"));
                wItem.CreateTime = StringUtils.parseCalendar(wReader.get("CreateTime"));
                wItem.EditID = StringUtils.parseInt(wReader.get("EditID"));
                wItem.EditTime = StringUtils.parseCalendar(wReader.get("EditTime"));

                wItem.ProductID = StringUtils.parseInt(wReader.get("ProductID"));
                wItem.ProductNo = StringUtils.parseString(wReader.get("ProductNo"));
                wItem.LineID = StringUtils.parseInt(wReader.get("LineID"));
                wItem.LineName = StringUtils.parseString(wReader.get("LineName"));
                wItem.CustomerID = StringUtils.parseInt(wReader.get("CustomerID"));
                wItem.CustomerName = StringUtils.parseString(wReader.get("CustomerName"));

                wItem.Creator = StringUtils.parseString(wReader.get("Creator"));
                wItem.Editor = StringUtils.parseString(wReader.get("Editor"));
                wItem.PartName = StringUtils.parseString(wReader.get("PartName"));
                wItem.PartPointName = StringUtils.parseString(wReader.get("PartPointName"));

                wResultList.add(wItem);
            }
        } catch (Exception ex) {
            wErrorCode.set(MESException.DBSQL.getValue());
            logger.error(ex.toString());
        }
        return wResultList;
    }
}
